import { expect } from '@jest/globals';
import fs from 'fs-extra';
import fsExtra from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

import { parseHar } from './openlab_aide_zos_build_shared_modules_packing_hos_api10_stage_001';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.NativeC,
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibraryWithC]: 1
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.Enable,
};
const testFun: TestCaseFun = async (project, taskConfig, record) => {

  const projectRootPath = project.projectRootPath();
  const command = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHar'
  });
  const result = await runHvigorAsync(projectRootPath, command);
  record.addStep('执行 assembleHar 任务', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 将生成的har 解析出来
  await parseHar(path.resolve(projectRootPath,
    'staticNativeCLibrary/build/default/outputs/default/'), 'staticNativeCLibrary');

  const harPath = path.resolve(projectRootPath,
    'staticNativeCLibrary/build/default/outputs/default/staticNativeCLibrary');

  // 判断是否有 ResourceTable.txt 文件
  const resourceTableExists = await fsExtra.pathExists(path.resolve(harPath, 'package/ResourceTable.txt'));
  expect(resourceTableExists).toBe(true);

  // 读取module.json 文件
  const buffer = await fs.readFile(path.resolve(harPath, 'package/src/main/module.json'));
  const parse = JSON.parse(buffer.toString());
  expect('app' in parse).toBe(true);
  expect('module' in parse).toBe(true);

  // 查看是否有cpp产物
  const cppExist = await fsExtra.pathExists(path.resolve(harPath, 'package/src/main/cpp'));
  expect(cppExist).toBe(true);

};

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_Shared_Modules_Packing_HOS_api10_STAGE_004')
  .description('Stage模型C++工程，ets+cpp共享模块打包')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
